public class Test {
}
class Solution {
    public int punishmentNumber(int n) {
        int ans = 0;
        for(int i=1; i<=n; i++){
            String s = String.valueOf(i*i);
            if(isValid(i,s,0,0)){
                ans += i*i;
                System.out.println(i*i);
            }
        }
        return ans;
    }
    private boolean isValid(int target, String s, int index, int sum){
        if(index == s.length() && target == sum) return true;
        for(int i=index; i<s.length(); i++){
            String t = s.substring(index,i+1);
            if(sum+Integer.parseInt(t)<=target && isValid(target,s,i+1,sum+Integer.parseInt(t)))
                return true;
        }
        return false;
    }
}